<?php
namespace app\common\helper;

class StringHelper
{
    /**
     * 生成随机字符串
     * @param int $length 长度
     * @param string $type 类型：alpha/number/all
     * @return string
     */
    public static function random($length = 6, $type = 'all')
    {
        $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '0123456789';
        
        switch($type) {
            case 'alpha':
                $chars = $alpha;
                break;
            case 'number':
                $chars = $number;
                break;
            default:
                $chars = $alpha . $number;
        }
        
        $str = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, $max)];
        }
        return $str;
    }

    /**
     * 截取字符串
     * @param string $str 字符串
     * @param int $length 长度
     * @param string $suffix 后缀
     * @return string
     */
    public static function truncate($str, $length, $suffix = '...')
    {
        if (mb_strlen($str) <= $length) {
            return $str;
        }
        return mb_substr($str, 0, $length) . $suffix;
    }
} 